import json
from typing import Annotated
from fastapi import APIRouter, Cookie, Request, Response, Depends, Form, File, UploadFile

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel
from application.http.schemas import ApiSchemas
from sanren.utils import Captcha, Tools
from sanren.extensions import ExtRedis, ExtQiniu
from application.config import appSettings


router = APIRouter(prefix='/common', tags=['公共接口'])
module_name = '公共接口'


__all__ = (router)


@router.post("/upload/image", summary='上传文件')
async def upload_image(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    brand_id: int = Form(None, description='品牌商 ID'),
    category_id: int = Form(None, description='图片分类 ID'),
    file: Annotated[UploadFile, File] = File(..., description='上传文件二进制文件'),
):
    """上传图片

    Args:
        current_user (object): 当前用户
        request (Request): 请求对象
        brand_id (int, optional): 品牌商 ID. Defaults to 0.
        category_id (int, optional): 图片分类 ID. Defaults to 0.
        file (Annotated[UploadFile, File], optional): 上传文件二进制文件. Defaults to File(...).

    Returns:
        json: 上传结果
    """
    if brand_id is not None and brand_id != 'null' and brand_id > 0:
        brand = OemModel.Company.where('brand_id', brand_id).first()
        if brand is None:
            return {'code': 1, 'message': '品牌商不存在'}
    if category_id is not None and category_id != 'null' and category_id > 0:
        category = OemModel.AssetCategory.find(category_id)
        if category is None:
            return {'code': 1, 'message': '图片分类不存在'}

    file_type = {'image/jpeg': '.jpeg', 'image/png': '.png', 'image/gif': '.gif', 'image/bmp': '.bmp'}

    content_type = file.headers.get('content-type')
    if content_type not in file_type.keys():
        return {'code': 1, 'message': '图片类型只支持: jpg/jpeg/png/bmp/gif'}
    # 文件大小 10M 限制
    if file.size > 10 * 1024 * 1024:
        return {'code': 1, 'message': '文件不能大于10M'}

    filename = file.filename
    try:
        contents = await file.read()
        # 上传到七牛云
        qiniu = ExtQiniu()
        hash_filename = Tools.generate_code(type='random', length=32) + file_type[content_type]
        key = f'{appSettings.file_prefix}/{hash_filename}'
        status, res = qiniu.put_data(key, contents)
        # print(res)
        if status is False:
            return {'code': 1, 'message': '上传失败'}

        # 保存到数据库
        data = {
            'brand_id': brand_id if brand_id is not None and brand_id != 'null' and brand_id > 0 else 0,
            'brand_code': brand.code if brand_id is not None and brand_id != 'null' and brand_id > 0 else None,
            'category_id': category_id if category_id is not None and category_id != 'null' and category_id > 0 else 0,
            'name': filename,
            'url': qiniu.domain,
            'path': key,
            'is_public': 1,
            'position': 1,
            'type': 1,
            'admin_id': current_user.id,
        }
        # OemModel.Asset.create(data)

        return {'code': 0, 'message': '上传成功', 'data': {**data, 'filename': filename, 'src': qiniu.get_url(key)}}
    except Exception as e:
        return {'code': 1, 'message': f'上传失败: {e}'}
